<?php
require_once 'init_app.php';

set_time_limit(0); 

$tags = DB::select()
            ->from('tags')
            ->where('id', '>', 1409)
            //->limit(10)
            ->execute()
            ->as_array();

$n = 0;
foreach ($tags as $tag) {
    $key = trim($tag['keyword']);
    $products = ORM::factory('product')->search($key, 1, $tag['category_id'], true);
    
    foreach ($products['products'] as $product) {
        try {
            DB::insert('product_tags', array('product_id', 'tag_id', 'sort'))
                    ->values(array($product['id'], $tag['id'], $product['weight']))->execute();
            $n++;
        } catch (Database_Exception $e) {
            if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                continue;
            }
            throw new Exception($e->getMessage());
        } 
    }  
}

echo $n."\n"; 
echo "ok\n";